package com.monkeyboy.rabbitmq.advanced_features.myconsumer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;

public class Consumer {
	public static void main(String[] args) throws Exception, ConsumerCancelledException, InterruptedException {
		// 1.创建连接工厂
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("localhost");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/myproject");
		connectionFactory.setUsername("Gavin");
		connectionFactory.setPassword("123456");
		// 2.获取到连接对象Connection
		Connection connection = connectionFactory.newConnection();

		// 3.通过Connection创建一个新的Channel
		Channel channel = connection.createChannel();

		String exchangeName = "test_consumer_exchange";
		String routingKey = "consumer.#";
		String queueName = "test_consumer_queue";
		// 声明交换机和队列
		channel.exchangeDeclare(exchangeName, "topic", true, false, null);
		channel.queueDeclare(queueName, false, false, false, null);
		// 绑定队列到交换机上
		channel.queueBind(queueName, exchangeName, routingKey);

		// 监听队列,自动签收
		channel.basicConsume(queueName, true, new MyConsumer(channel));
	}
}
